package br.com.linkin.mi.soap;

import br.com.linkin.mi.utils.log.Logger;
import java.io.InputStream;
import java.io.StringReader;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.stream.StreamSource;
import javax.xml.validation.Schema;
import javax.xml.validation.SchemaFactory;
import javax.xml.validation.Validator;
import org.xml.sax.InputSource;
import org.xml.sax.SAXParseException;

/**
 *
 * @author daniel.mendonca
 */
public class Validation {
    
    private final static String SCHEMA_LANG = "http://www.w3.org/2001/XMLSchema";    
    private final static SchemaFactory FACTORY = SchemaFactory.newInstance(SCHEMA_LANG);
    
    /**
     * validar XML
     * @param xml
     * @param xsd
     * @return 
     */
    public static Boolean validarXML(String xml, String xsd){
        
        try {
            
            InputStream xsdFile = Validation.class.getResourceAsStream("/schemas/v1_04/xsd/" + xsd);

            Schema schema = FACTORY.newSchema(new StreamSource(xsdFile));
            Validator validator = schema.newValidator();
            //Perform the validation:
            validator.validate(new StreamSource(new StringReader(xml)));
            DocumentBuilderFactory fact = DocumentBuilderFactory.newInstance();
            DocumentBuilder builder = fact.newDocumentBuilder();
            builder.parse(new InputSource(new StringReader(xml)));
            
        } catch (SAXParseException e) {            
            StringBuilder msg = new StringBuilder();
            msg.append("Erro de validaçao na Coluna: ")
               .append(((SAXParseException) e).getColumnNumber())
               .append(" | Linha: ")
               .append(((SAXParseException) e).getLineNumber())
               .append(" - Exception: ")
               .append(((SAXParseException) e).getLocalizedMessage());

            Logger.erro(msg.toString());
            return false;
            
        } catch (Exception e) {
            StringBuilder msg = new StringBuilder();
            msg.append("Unknow error attemping to validate XML.");

            Logger.erro(msg.toString(), e); 
            
            return false;
        }
        return true;
    }    
}
